import { CheckCircleFilled, InfoCircleFilled } from '@ant-design/icons'
import { App, Col, Form, Input, Modal, Row } from 'antd'
import cs from 'classnames'
import { Dispatch, SetStateAction, useContext, useEffect } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'

import { Violation } from '@/api/interface'
import arrowPre from '@/assets/arrow-pre.png'
import del from '@/assets/delete.png'
import { showFullScreenLoading, tryHideFullScreenLoading } from '@/components/Loading/fullScreen'
import { GlobalState } from '@/store'
import { onCreate } from '@/syncData'

import styles from '../styles/index.module.less'

const { TextArea } = Input

interface Props {
  t: any
  lang: string
  cancel: () => void
  setSetup: Dispatch<SetStateAction<number>>
  violation: Partial<Violation>
  setViolation: Dispatch<SetStateAction<Partial<Violation>>>
}

function InvestigationClosure({ t, lang, cancel, setSetup, violation, setViolation }: Props) {
  const { modal } = App.useApp()
  const [form] = Form.useForm()
  const router = useHistory()

  useEffect(() => {
    form.setFieldsValue({
      ...violation,
    })
  }, [])

  const FormLabel = ({ title, required = true }: { title: string; required?: boolean }) => {
    return (
      <span className={styles['form-item-label']}>
        {title}
        {required && <span className={styles['form-item-label-required']}>*</span>}
      </span>
    )
  }

  const { orgName } = useSelector((state: GlobalState) => state)

  const contextText = () => {
    if (lang === 'ar-EG') {
      return `تم حفظ التحقيق في وضع عدم الاتصال. اتصل بشبكة ${orgName} لمزامنتها مع منصة واجب.`
    } else {
      return `The investigation has been saved offline. Connect to ${orgName} network to sync it to Wajib platform.`
    }
  }

  const confirm = () => {
    modal.confirm({
      title: t['form.notice.title'],
      content: t['form.closeConfirm.title'],
      icon: <InfoCircleFilled style={{ color: '#44C5E4' }} />,
      className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
      closable: true,
      okText: t['form.button.submit'],
      cancelText: t['form.button.cancel'],
      // keyboard: false,
      onOk() {
        form.submit()
      },
    })
  }

  const onFinish = async (values: Partial<Violation>) => {
    const data: Partial<Violation> = JSON.parse(JSON.stringify(violation))
    data.details.forEach((item) => {
      item.attachment = item.attachment.map((item) => item.path)
      item.questions.forEach((v) => {
        v.attachment = v.attachment.map((item) => item.path)
      })
    })

    // 删除掉没有完成签名的
    data.details = data.details.filter((detail) => !data.undoneSignatureEid.includes(detail.eid))

    // 去掉 eid 连接符
    data.details = data.details.map((item) => {
      item.eid = item.eid.replace(/-/g, '')
      return item
    })

    const params = {
      ...data,
      eid: data.eid.replace(/-/g, ''),
      closureSummary: values.closureSummary,
      closureAction: values.closureAction?.length
        ? values.closureAction.map((item) => item.action).filter((item) => item)
        : [],
    }

    try {
      showFullScreenLoading()
      await onCreate(params)
      modal.info({
        title: t['form.notice.title'],
        icon: <CheckCircleFilled style={{ color: '#00B42A' }} />,
        className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
        closable: true,
        content: t['form.notice.content.success'],
        okText: t['form.button.ok'],
        keyboard: false,
        onOk() {
          router.push('/')
        },
        onCancel() {
          router.push('/')
        },
      })
    } catch (error) {
      modal.info({
        title: t['form.notice.title'],
        icon: <InfoCircleFilled style={{ color: '#44C5E4' }} />,
        className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
        closable: true,
        content: t['form.notice.content.offline'],
        okText: t['form.button.ok'],
        keyboard: false,
        onOk() {
          router.push('/')
        },
        onCancel() {
          router.push('/')
        },
      })
    } finally {
      tryHideFullScreenLoading()
    }
  }

  const onValuesChange = (_, allValues: Partial<Violation>) => {
    setViolation({ ...violation, ...allValues })
  }

  const preventEnterSubmit = (event: any) => {
    if (['Enter', 'enter'].includes(event.key)) {
      event.preventDefault()
    }
  }

  return (
    <div className={styles['form-closure']}>
      <Form
        layout="vertical"
        name="closure"
        form={form}
        onFinish={onFinish}
        onValuesChange={onValuesChange}
        onKeyDown={preventEnterSubmit}
      >
        <Row gutter={24}>
          <Col xs={24}>
            <Form.Item label={<FormLabel title={t['form.closure.summary']} />}>
              <Form.Item
                name="closureSummary"
                rules={[{ required: true, message: t['form.closure.summary.error'] }]}
              >
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  // placeholder={t['form.closure.summary']}
                />
              </Form.Item>
            </Form.Item>
          </Col>

          <Col span={24} className={styles['form-closure-action']}>
            <span className={styles['form-title-h4']}>{t['form.closure.action']}</span>
            <Form.List name="closureAction">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }, index) => (
                    <div key={key} className={styles['form-closure-action-item']}>
                      <Form.Item
                        label={
                          <FormLabel
                            title={`${t['form.closure.action.item']} ${index + 1}`}
                            required={false}
                          />
                        }
                      >
                        <Form.Item
                          {...restField}
                          name={[name, 'action']}
                          // rules={[
                          //   {
                          //     required: true,
                          //     message: t['form.closure.action.item.error'],
                          //   },
                          // ]}
                        >
                          <Input
                            maxLength={500}
                            // placeholder={t['form.closure.action.item']}
                          />
                        </Form.Item>
                      </Form.Item>
                      <img
                        onClick={() => remove(name)}
                        src={del}
                        style={lang === 'en-US' ? { right: '20px' } : { left: '20px' }}
                        className={styles['form-closure-action-del']}
                        alt="del"
                      />
                    </div>
                  ))}
                  <Form.Item>
                    <span onClick={() => add()} className={styles['form-closure-action-add']}>
                      {t['form.closure.action.add']}
                    </span>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Col>
        </Row>
        <div className={styles['form-button']}>
          <div className={styles['form-button-left']}>
            <div className={styles['form-button-pre']} onClick={() => cancel()}>
              <span className={styles['button-text']}>{t['form.button.cancel']}</span>
            </div>
            <div className={styles['form-button-pre']} onClick={() => setSetup(2)}>
              <img src={arrowPre} className={styles['button-icon']} alt="pre" />
              <span className={styles['button-text']}>{t['form.button.previous']}</span>
            </div>
          </div>
          <div className={styles['form-button-next']} onClick={() => confirm()}>
            <span className={styles['button-text']}>{t['form.button.submit']}</span>
          </div>
        </div>
      </Form>
    </div>
  )
}

export default InvestigationClosure
